<template>
  <div id="trainingCandidates">
    <el-dialog :title="'干部'+(deptId===1?'一':(deptId===2?'二':'三'))+'处人选建议'" :visible.sync="personVisible" width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false" >
      <div id="trainEditTable">
        <el-dialog title="手动添加人选" append-to-body :visible.sync="addFormVisible" width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false">
          <additional-person-detail :deptId="deptId" :classId="classId" type="recommended" @refreshRecommented="refreshRecommented(false)" :timestamp="timestamp" />
        </el-dialog>
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="人选建议" name="formal">
            <el-form :inline="true">
              <el-form-item label="" prop="Name">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-arrow-up" :loading="btnLoading" @click="moveData(1,'recommended')" :disabled="!moveUpFlag">上移</el-button>
                  <el-button type="primary" icon="el-icon-arrow-down" :loading="btnLoading" @click="moveData(2,'recommended')" :disabled="!moveDownFlag">下移</el-button>
                </el-button-group>
              </el-form-item>
              <el-form-item label="" prop="Name">
                <el-button type="success" @click="addPerson">从人员列表中新增人选</el-button>
                <!-- <el-dropdown type="success" split-button  @click="additionalPerson" v-if="showAdditional">
                  手动添加人选
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="additionalPersonList" >在已手动添加人选列表中选择</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button v-else type="success" @click="additionalPerson">手动添加人选</el-button> -->
                <el-button type="success" @click="additionalPersonList">从已手动添加人选列表中新增人选</el-button>
              </el-form-item>
            </el-form>
            <el-table :data="formatPersonList" class="el-table" style="width:100%" border ref="multipleTable" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="40" />
              <el-table-column width="50" type="index" label="序号" align="center"></el-table-column>
              <el-table-column width="90" property="name" label="姓名" align="center">
                <div style="margin:10px 0;" slot-scope="scope">
                  {{scope.row.name}}
                </div>
              </el-table-column>
              <el-table-column width="50" property="age" label="年龄" align="center"></el-table-column>
              <el-table-column min-width="150" property="unit" label="单位"></el-table-column>
              <el-table-column width="200" property="job" label="职务"></el-table-column>
              <el-table-column width="100" property="level" label="级别" align="center"></el-table-column>
              <el-table-column width="90" prop="partyMember" label="是否党员" align="center">
                <template slot-scope="scope">
                  {{scope.row.partyMember?'是':'否'}}
                </template>
              </el-table-column>
              <el-table-column width="230" property="jobDate" label="任相当层次职务职级时间">
                <div style="margin:10px 0;" slot-scope="scope">
                  <!-- <el-date-picker v-model="scope.row.jobDate" placeholder="选择日期" @change="editPerson(scope.row.id,'jobDate',scope.row.jobDate)"  style="width:150px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" /> -->
                  <!-- <el-input v-model="scope.row.jobDate" auto-complete="off" style="width:150px;" @change="editPerson(scope.row.id,'jobDate',scope.row.jobDate)" :maxlength="8"></el-input>
                  <el-tooltip class="item" effect="dark" content="格式：20201001或202010" placement="top">
                    <el-button type="text" icon="el-icon-info" />
                  </el-tooltip> -->
                  {{formatJobDate(scope.row.jobDate)}}
                </div>
              </el-table-column>
              <el-table-column width="230" property="remark" label="备注">
                <div style="margin:10px 0;" slot-scope="scope">
                  <el-input v-model="scope.row.remarks" auto-complete="off" style="width:200px;" @change="editPerson(scope.row.id,'remarks',scope.row.remarks)" :maxlength="500"></el-input>
                </div>
              </el-table-column>
              <el-table-column width="120" property="name" label="操作">
                <div style="margin:10px 0;" slot-scope="scope">
                  <el-button type="danger" size="small" @click="handleDel(scope.row.id)" :loading="btnLoading" style="margin:10px 0">删除</el-button>
                </div>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="人员筛选" name="search">
            <filed-candidate :classId="classId" :deptId="deptId" type="recommended" @refreshRecommented="refreshRecommented(true)" />
          </el-tab-pane>
          <el-tab-pane label="已手动添加人选列表" name="additional">
            <el-button type="success" @click="additionalPerson" style="float:right;position:absolute;right:60px;top:20px;z-index:99999">手动添加人选</el-button>
            <additional-person :classId="classId" :deptId="deptId" type="recommended" @refreshRecommented="refreshRecommented(true)" :timestamp="timestamp" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
    <el-dialog :title="'参训人选'+(cond?'（班次条件：'+cond+'）':'')" :visible.sync="personVisible1" width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false" >
      <div id="trainEditTable">

        <el-dialog title="手动添加人选" append-to-body :visible.sync="addFormVisible" width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false">
          <additional-person-detail :classId="classId" type="official" @refreshRecommented="refreshRecommented(false)" :timestamp="timestamp"  />
        </el-dialog>

        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="参训人选" name="formal">
            <el-form :inline="true">
              <el-form-item label="" prop="Name">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-arrow-up" :loading="btnLoading" @click="moveData(1,'official')" :disabled="!moveUpFlag">上移</el-button>
                  <el-button type="primary" icon="el-icon-arrow-down" :loading="btnLoading" @click="moveData(2,'official')" :disabled="!moveDownFlag">下移</el-button>
                </el-button-group>
              </el-form-item>
              <el-form-item label="" prop="Name">
                <el-button type="success" @click="addPerson">从人员列表中新增人选</el-button>
                <!-- <el-dropdown type="success" split-button  @click="additionalPerson" v-if="showAdditional">
                  手动添加人选
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="additionalPersonList" ></el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown> -->
                <el-button type="success" @click="additionalPersonList">从已手动添加人选列表中新增人选</el-button>
              </el-form-item>
            </el-form>
            <el-table :data="formatPersonList" class="el-table" style="width:100%" border ref="multipleTable" @selection-change="handleSelectionChange2">
              <el-table-column type="selection" width="40" />
              <el-table-column width="110" prop="typename" label="类型">
                <template slot-scope="scope">
                  <el-tooltip
                    v-if="scope.row.type===1&&!scope.row.participation"
                    placement="top"
                    :content="'未参训，原因：'+scope.row.reason"
                    >
                    <el-tag type="warning" effect="dark"><b>{{scope.row.typename}}</b></el-tag>
                  </el-tooltip>
                  <el-tag v-if="scope.row.type===1&&scope.row.participation" type="'success'" effect="dark"><b>{{scope.row.typename}}</b></el-tag>
                  <el-tag v-if="scope.row.type===2" type="info" effect="dark"><b>{{scope.row.typename}}</b></el-tag>
                </template>
              </el-table-column>
              <el-table-column width="90" property="name" label="姓名">
                <div style="margin:10px 0;" slot-scope="scope">
                  {{scope.row.name}}
                </div>
              </el-table-column>
              <el-table-column width="50" property="age" label="年龄"></el-table-column>
              <el-table-column min-width="150" property="unit" label="单位"></el-table-column>
              <el-table-column width="250" property="job" label="职务"></el-table-column>
              <el-table-column width="100" property="level" label="级别"></el-table-column>
              <el-table-column width="80" prop="partyMember" label="是否党员" align="center">
                <template slot-scope="scope">
                  {{scope.row.partyMember?'是':'否'}}
                </template>
              </el-table-column>
              <el-table-column width="230" property="jobDate" label="任相当层次职务职级时间">
                <div style="margin:10px 0;" slot-scope="scope">
                  <!-- <el-date-picker v-model="scope.row.jobDate" placeholder="选择日期" @change="editPerson(scope.row.id,'jobDate',scope.row.jobDate,'official')" style="width:150px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" /> -->
                  <!-- <el-input v-model="scope.row.jobDate" auto-complete="off" style="width:150px;" @change="editPerson(scope.row.id,'jobDate',scope.row.jobDate,'official')" :maxlength="8"></el-input>
                  <el-tooltip class="item" effect="dark" content="格式：20201001或202010" placement="top">
                    <el-button type="text" icon="el-icon-info" />
                  </el-tooltip> -->
                  {{formatJobDate(scope.row.jobDate)}}
                </div>
              </el-table-column>
              <el-table-column width="230" property="remarks" label="备注">
                <div style="margin:10px 0;" slot-scope="scope">
                  <el-input v-model="scope.row.remarks" auto-complete="off" style="width:200px;" @change="editPerson(scope.row.id,'remarks',scope.row.remarks,'official')" :maxlength="500"></el-input>
                </div>
              </el-table-column>
              <el-table-column width="230" property="name" label="操作">
                <div style="margin:10px 0;" slot-scope="scope">
                  <el-button v-if="scope.row.type===1&&scope.row.participation" type="warning" size="small" @click="setReason(scope.row.id,false)" :loading="btnLoading" style="margin:10px 0;color:#fff !important">未参训</el-button>
                  <el-button v-if="scope.row.type===1&&!scope.row.participation" type="success" size="small" @click="setReason(scope.row.id,true)" :loading="btnLoading" style="margin:10px 0;color:#fff !important">取消未参训</el-button>
                  <el-button type="danger" size="small" @click="handleDel(scope.row.id,'official')" :loading="btnLoading" style="margin:10px 0">删除</el-button>
                </div>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="干部处人选建议" name="proposal">
            <el-row :gutter="10">
              <!-- <el-col :span="classNum?(24/classNum):24" v-if="classList1&&classList1.length>0"> -->
              <el-col :span="24" v-if="classList1&&classList1.length>0">
                <h3>干部一处</h3>
                <el-table :data="classList1" class="el-table" style="width:100%">
                  <el-table-column width="50" type="index" label="序号" align="center"></el-table-column>
                  <el-table-column width="90" property="name" label="姓名" align="center"></el-table-column>
                  <el-table-column min-width="180" property="unit" label="单位"></el-table-column>
                  <el-table-column width="300" property="name" label="操作">
                    <div slot-scope="scope">
                      <el-button type="success" size="small" @click="handleAdd(scope.row.id,1)" :loading="btnLoading" style="margin:10px 0">选为参训人选</el-button>
                      <el-button type="primary" size="small" @click="handleAdd(scope.row.id,2)" :loading="btnLoading" style="margin:10px 0">选为备选人选</el-button>
                    </div>
                  </el-table-column>
                </el-table>
              </el-col>
              <!-- <el-col :span="classNum?(24/classNum):24" v-if="classList2&&classList2.length>0"> -->
              <el-col :span="24" v-if="classList2&&classList2.length>0">
                <h3>干部二处</h3>
                <el-table :data="classList2" class="el-table" style="width:100%">
                  <el-table-column width="50" type="index" label="序号" align="center"></el-table-column>
                  <el-table-column width="90" property="name" label="姓名" align="center"></el-table-column>
                  <el-table-column min-width="180" property="unit" label="单位"></el-table-column>
                  <el-table-column width="300" property="name" label="操作">
                    <div slot-scope="scope">
                      <el-button type="success" size="small" @click="handleAdd(scope.row.id,1)" :loading="btnLoading" style="margin:10px 0">选为参训人选</el-button>
                      <el-button type="primary" size="small" @click="handleAdd(scope.row.id,2)" :loading="btnLoading" style="margin:10px 0">选为备选人选</el-button>
                    </div>
                  </el-table-column>
                </el-table>
              </el-col>
              <!-- <el-col :span="classNum?(24/classNum):24" v-if="classList3&&classList3.length>0"> -->
              <el-col :span="24" v-if="classList3&&classList3.length>0">
                <h3>干部三处</h3>
                <el-table :data="classList3" class="el-table" style="width:100%">
                  <el-table-column width="50" type="index" label="序号" align="center"></el-table-column>
                  <el-table-column width="90" property="name" label="姓名" align="center"></el-table-column>
                  <el-table-column min-width="180" property="unit" label="单位"></el-table-column>
                  <el-table-column width="300" property="name" label="操作">
                    <div slot-scope="scope">
                      <el-button type="success" size="small" @click="handleAdd(scope.row.id,1)" :loading="btnLoading" style="margin:10px 0">选为参训人选</el-button>
                      <el-button type="primary" size="small" @click="handleAdd(scope.row.id,2)" :loading="btnLoading" style="margin:10px 0">选为备选人选</el-button>
                    </div>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="人员筛选" name="search">
            <filed-candidate :classId="classId" type="official" @refreshRecommented="refreshRecommented(true)" />
          </el-tab-pane>
          <el-tab-pane label="已手动添加人选列表" name="additional">
            <el-button type="success" @click="additionalPerson" style="float:right;position:absolute;right:60px;top:20px;z-index:99999">手动添加人选</el-button>
            <additional-person :classId="classId" :timestamp="timestamp" type="official" @refreshRecommented="refreshRecommented(true)" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
    <el-dialog title="未参训原因" :visible.sync="reasonVisible" width="650px" :close-on-click-modal="false" :close-on-press-escape="false" >
      <el-input v-model="reason" auto-complete="off" style="width:500px;margin-right:10px" :maxlength="200" /><el-button :loading="btnLoading" @click="submitReason" type="success">保存</el-button>
    </el-dialog>
    <template v-if="formatPersonList&&formatPersonList.length>0">
      <template v-if="type==='official'">
        <el-tooltip v-for="(item,index) in formatPersonList" :key="'official'+index"
          class="item"
          effect="dark"
          :content="item.typename+((item.type===1&&!item.participation)?('（未参训，原因：'+item.reason)+'）':'')"
          placement="top"
          >
          <el-tag style="margin-right:5px;margin-bottom:5px" :type="item.theType" effect="dark">{{item.name}}</el-tag>
        </el-tooltip>
      </template>
      <template v-else>
        <el-tag v-for="(item,index) in formatPersonList" :key="'recommented'+index" style="margin-right:5px;margin-bottom:5px">{{item.name}}</el-tag>
      </template>
      <el-popover
        v-if="!canEdit"
        placement="bottom"
        trigger="hover">
        <template v-if="type==='official'">
          <h1>
            参训人选
          </h1>
          <el-table :data="formatPersonList" class="el-table">
            <el-table-column width="60" type="index" label="序号" align="center" />
            <el-table-column width="120" prop="typename" label="类型">
              <template slot-scope="scope">
                <el-tooltip
                  v-if="scope.row.type===1&&!scope.row.participation"
                  placement="top"
                  :content="'未参训，原因：'+scope.row.reason"
                  >
                  <el-tag type="warning" effect="dark"><b>{{scope.row.typename}}</b></el-tag>
                </el-tooltip>
                <el-tag v-if="scope.row.type===1&&scope.row.participation" type="'success'" effect="dark"><b>{{scope.row.typename}}</b></el-tag>
                <el-tag v-if="scope.row.type===2" type="info" effect="dark"><b>{{scope.row.typename}}</b></el-tag>
              </template>
            </el-table-column>
            <el-table-column width="120" prop="name" label="姓名" />
            <el-table-column width="60" prop="age" label="年龄" align="center" />
            <el-table-column width="150" prop="unit" label="单位" />
            <el-table-column width="180" prop="job" label="职务" />
            <el-table-column width="100" prop="level" label="级别" />
            <el-table-column width="60" prop="partyMember" label="是否党员" align="center">
              <template slot-scope="scope">
                {{scope.row.partyMember?'是':'否'}}
              </template>
            </el-table-column>
            <el-table-column width="110" prop="jobDate" label="任相当层次职务职级时间" align="center">
              <template slot-scope="scope" >
                {{formatJobDate(scope.row.jobDate)}}
              </template>
            </el-table-column>
            <el-table-column width="200" prop="remarks" label="备注" />
          </el-table>
        </template>
        <template v-else>
          <h1>
            干部{{(deptId===1?'一':(deptId===2?'二':'三'))}}处人选建议
          </h1>
          <el-table :data="formatPersonList" class="el-table">
            <el-table-column width="60" type="index" label="序号" />
            <el-table-column width="90" property="name" label="姓名" />
            <el-table-column width="60" property="age" label="年龄" />
            <el-table-column width="150" property="unit" label="单位" />
            <el-table-column width="180" property="job" label="职务" />
            <el-table-column width="100" property="level" label="级别" />
            <el-table-column width="60" property="partyMember" label="是否党员">
              <template slot-scope="scope">
                {{scope.row.partyMember?"是":"否"}}
              </template>
            </el-table-column>
            <el-table-column width="110" property="jobDate" label="任相当层次职务职级时间">
              <template slot-scope="scope" >
                {{formatJobDate(scope.row.jobDate)}}
              </template>
            </el-table-column>
            <el-table-column width="200" property="remarks" label="备注" />
          </el-table>
        </template>
        <i class="el-icon-search" slot="reference" />
      </el-popover>
    </template>
    <i class="el-icon-edit" v-if="canEdit" @click="handleEditPerson" style="cursor:pointer" />
  </div>
</template>

<script>
import filedCandidate from './filedCandidate.vue'
import additionalPerson from './additionalPerson.vue'
import additionalPersonDetail from './additionalPersonDetail.vue'
export default {
  components: { filedCandidate, additionalPerson, additionalPersonDetail },
  watch: {
    candidateList: {
      handler (val) {
        this.formatPersons()
        if (this.classId && this.canEdit && this.type === 'official') {
          this.getAllRecommended()
        }
      },
      immediate: true
    },
    type: {
      handler (val) {
        this.formatPersons()
      },
      immediate: true
    }
    // classId: {
    //   handler (val) {
    //     if (val && this.canEdit && this.type === 'official') {
    //       this.getAllRecommended()
    //     }
    //   },
    //   immediate: true
    // }
  },
  props: {
    cond: '',
    candidateList: [],
    type: null,
    deptId: null,
    classId: null,
    canEdit: false,
    personNumber: null
  },
  data () {
    return {
      timestamp: null,
      addFormVisible: false,
      showAdditional: false,
      moveUpFlag: false,
      moveDownFlag: false,
      multipleSelection: [],
      shhlist2: [
      ],
      gridData: [
      ],
      viewtype: 1,
      filters: {},
      gridData1: [
      ],
      gridData3: [
      ],
      gridData4: [
      ],
      saveLoading: false,
      addForm: {
        name: ''
      },
      addFormRules: {
        name: [
          { required: true, message: '必填项', trigger: 'blur' }
        ]
      },
      yearlist: [],
      listLoading: false,
      btnLoading: false,
      activeName: 'formal',
      personVisible: false,
      personVisible1: false,
      formatPersonList: [],
      classList1: [],
      classList2: [],
      classList3: [],
      classNum: 0,
      reasonVisible: false,
      reason: '',
      participationId: null,
      participation: null
    }
  },
  methods: {
    formatJobDate (str) {
      if (str) {
        if (str.length === 6 && /^[0-9]*$/.test(str)) { // yyyymm
          return str.substr(0, 4) + '.' + str.substr(4)
        }
        if (str.length === 8 && /^[0-9]*$/.test(str)) { // yyyymmdd
          return str.substr(0, 4) + '.' + str.substr(4, 2) + '.' + str.substr(6, 2)
        } else {
          return str
        }
      }
    },
    getAdditionalList () {
      let team = null
      if (this.deptId) {
        team = this.deptId
      }
      let para = {
        pageNum: 1,
        pageSize: 1,
        team: team
      }
      let url = 'api/trainingAdditionalPerson/queryByPage'
      this.$http
        .post(this.$http.defaults.trainingAPI + url, para)
        .then(response => {
          this.listLoading = false
          if (response.data.success === true) {
            console.log('获取成功')
            let arr = response.data.result.records
            this.showAdditional = arr && arr.length > 0
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    setReason (id, participation) {
      this.reason = ''
      this.participation = participation
      this.participationId = id
      if (participation) {
        this.submitReason()
      } else {
        this.reasonVisible = true
      }
    },
    submitReason () {
      if (!this.participation && !this.reason) {
        this.$message({
          message: '未参训请填写原因',
          type: 'error'
        })
        return
      }
      let para = {
        id: this.participationId,
        participation: this.participation,
        reason: this.reason
      }
      this.btnLoading = true
      this.$http.post(this.$http.defaults.trainingAPI + `api/trainingBusOfficialCandidate/updateParticipation`, para).then(response => {
        console.log(response.data.success)
        this.btnLoading = false
        if (response.data.success === true) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          console.log('操作成功:' + response.data.message)
          this.reasonVisible = false
          this.refreshRecommented()
        } else {
          console.log('操作失败:' + response.data.message)
          this.$message({
            message: '操作失败:' + response.data.message,
            type: 'error'
          })
        }
      }).catch((error) => {
        this.btnLoading = false
        console.log(error)
        this.$message({
          message: '保存失败:' + error,
          type: 'error'
        })
      })
    },
    handleAdd (id, type) {
      if (type === 1) {
        let officialNum = this.formatPersonList.filter(item => item.type === 1 && item.participation).length
        if (officialNum < this.personNumber) {
          this.addfunction(id, type)
        } else {
          this.$confirm('该班次培训人数为' + this.personNumber + '人，已添加参训人员' + officialNum + '人，是否继续添加？', '提示', {
            type: 'warning'
          }).then(() => {
            this.addfunction(id, type)
          })
        }
      } else {
        this.addfunction(id, type)
      }
    },
    addfunction (id, type) {
      let para = {id: id, type: type}
      this.btnLoading = true
      this.$http.post(this.$http.defaults.trainingAPI + `api/trainingBusRecommendedCandidate/updateToOfficial`, para).then(response => {
        console.log(response.data.success)
        this.btnLoading = false
        if (response.data.success === true) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          console.log('操作成功:' + response.data.message)
          this.refreshRecommented()
        } else {
          console.log('操作失败:' + response.data.message)
          this.$message({
            message: '操作失败:' + response.data.message,
            type: 'error'
          })
        }
      }).catch(error => {
        this.btnLoading = false
        console.log(error)
        this.$message({
          message: '保存失败:' + error,
          type: 'error'
        })
      })
    },
    getAllRecommended () {
      this.classNum = 0
      this.getRecommendedCandidateList(1)
      this.getRecommendedCandidateList(2)
      this.getRecommendedCandidateList(3)
    },
    getRecommendedCandidateList (deptId) {
      this.$http
        .get(this.$http.defaults.trainingAPI + `api/trainingBusClass/getRecommendedCandidateList?deptId=` + deptId + `&classId=` + this.classId)
        .then(response => {
          if (response.data.success === true) {
            this['classList' + deptId] = response.data.result
            if (this['classList' + deptId].length > 0) {
              this.classNum++
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    isDate8 (sDate) {
      if (!/^[0-9]{8}$/.test(sDate)) {
        return false
      }
      var year, month, day
      year = sDate.substring(0, 4)
      month = sDate.substring(4, 6)
      day = sDate.substring(6, 8)
      var iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
      if (year < 1700 || year > 2500) return false
      if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) iaMonthDays[1] = 29
      if (month < 1 || month > 12) return false
      if (day < 1 || day > iaMonthDays[month - 1]) return false
      return true
    },
    isDate6 (sDate) {
      if (!/^[0-9]{6}$/.test(sDate)) {
        return false
      }
      var year, month
      year = sDate.substring(0, 4)
      month = sDate.substring(4, 6)
      if (year < 1700 || year > 2500) return false
      if (month < 1 || month > 12) return false
      return true
    },
    editPerson (id, key, value, type) {
      let tableName = 'trainingBusRecommendedCandidate'
      if (type === 'official') {
        tableName = 'trainingBusOfficialCandidate'
      }
      let para = {
        id: id
      }
      para[key] = value
      if (key === 'jobDate' && !this.isDate8(para[key]) && !this.isDate6(para[key]) && para[key]) {
        this.$message({
          message: '任相当层次职务职级时间保存失败：格式有误，格式：20201001或202010',
          type: 'error'
        })
        return false
      }
      this.$http.post(this.$http.defaults.trainingAPI + `api/` + tableName + `/save`, para).then(response => {
        console.log(response.data.success)
        if (response.data.success === true) {
          console.log('操作成功:' + response.data.message)
        } else {
          console.log('操作失败:' + response.data.message)
          this.$message({
            message: '操作失败:' + response.data.message,
            type: 'error'
          })
        }
      }).catch((error) => {
        console.log(error)
        this.$message({
          message: '保存失败:' + error,
          type: 'error'
        })
      })
    },
    handleDel (id, type) {
      let tableName = 'trainingBusRecommendedCandidate'
      if (type === 'official') {
        tableName = 'trainingBusOfficialCandidate'
      }
      this.$confirm('确认删除该人选吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.btnLoading = true
        let para = {ids: [id]}
        this.listLoading = true
        this.$http.post(this.$http.defaults.trainingAPI + `api/` + tableName + `/remove`, para).then(response => {
          this.btnLoading = false
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            console.log('reloadBatch')
            this.$emit('reloadBatch')
          } else {
            console.log('删除失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
        })
      })
    },
    refreshRecommented (flag) {
      this.timestamp = new Date().getTime()
      this.addFormVisible = false
      this.getAdditionalList()
      if (flag) {
        this.activeName = 'formal'
      }
      this.$emit('reloadBatch')
    },
    handleSave () {
    },
    searchPrj () {},
    searchList () {},
    addPerson () {
      this.activeName = 'search'
    },
    additionalPerson () {
      this.timestamp = new Date().getTime()
      this.addFormVisible = true
    },
    additionalPersonList () {
      this.activeName = 'additional'
    },
    handleSelectionChange (val) {
      localStorage.removeItem('trainingSelectId')
      this.moveUpFlag = false
      this.moveDownFlag = false
      this.multipleSelection = val
      if (this.multipleSelection.length === 1) {
        this.moveUpFlag = true
        this.moveDownFlag = true
        if (this.formatPersonList.findIndex(item => item.id === this.multipleSelection[0].id) === 0) {
          this.moveUpFlag = false
        }
        if (this.formatPersonList.findIndex(item => item.id === this.multipleSelection[0].id) === this.formatPersonList.length - 1) {
          this.moveDownFlag = false
        }
      }
    },
    handleSelectionChange2 (val) {
      localStorage.removeItem('trainingSelectId')
      this.moveUpFlag = false
      this.moveDownFlag = false
      this.multipleSelection = val
      if (this.multipleSelection.length === 1) {
        this.moveUpFlag = true
        this.moveDownFlag = true
        if (this.formatPersonList.findIndex(item => item.id === this.multipleSelection[0].id) === 0) {
          this.moveUpFlag = false
        }
        if (this.formatPersonList.findIndex(item => item.id === this.multipleSelection[0].id) === this.formatPersonList.length - 1) {
          this.moveDownFlag = false
        }
      }
    },
    toggleSelection (id) {
      this.$nextTick(() => {
        if (id) {
          let newrow = this.formatPersonList.find(item => item.id === id)
          if (newrow) {
            this.$refs.multipleTable.toggleRowSelection(newrow)
            localStorage.removeItem('trainingSelectId')
          }
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      })
    },
    moveData (flag, type, changeType) {
      let tableName = 'trainingBusRecommendedCandidate'
      if (type === 'official') {
        tableName = 'trainingBusOfficialCandidate'
        let selectItem = this.multipleSelection[0]
        if (!changeType) {
          if (selectItem.type === 1 && this.formatPersonList.filter(item => item.dataOrder > selectItem.dataOrder && item.type === 1).length === 0 && flag === 2) {
            this.$confirm('所选人选已经是参训人选里最后一位，是否将其调整为备选人选，同时将备选人选第一位调整为参训人选?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.moveData(flag, type, true)
            }).catch(() => {
            })
            return
          }
          if (selectItem.type === 2 && this.formatPersonList.filter(item => item.dataOrder < selectItem.dataOrder && item.type === 2).length === 0 && flag === 1) {
            this.$confirm('所选人选已经是备选人选里第一位，是否将其调整为参训人选，同时将参训人选最后一位调整为备选人选?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.moveData(flag, type, true)
            }).catch(() => {
            })
            return
          }
        }
      }
      this.btnLoading = true
      let para = {
        id: this.multipleSelection[0].id,
        direction: flag
      }
      this.$http.post(this.$http.defaults.trainingAPI + `api/` + tableName + `/switchOrder`, para).then(response => {
        console.log(response.data.success)
        if (response.data.success === true) {
          this.btnLoading = false
          localStorage.setItem('trainingSelectId', this.multipleSelection[0].id)
          this.$emit('reloadBatch')
        } else {
          console.log('调整顺序失败:' + response.data.message)
          this.$message({
            message: '调整顺序失败:' + response.data.message,
            type: 'error'
          })
          this.btnLoading = false
        }
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '调整顺序失败:' + error,
          type: 'error'
        })
        this.btnLoading = false
      })
    },
    handleEditPerson () {
      this.getAdditionalList()
      if (this.type === 'recommended') {
        this.personVisible = true
      } else if (this.type === 'official') {
        this.personVisible1 = true
      }
    },
    formatPersons () {
      if (this.type === 'recommended') {
        if (this.candidateList && this.candidateList.length > 0) {
          this.formatPersonList = this.candidateList.filter(item => item.deptId === this.deptId)
        } else {
          this.formatPersonList = []
        }
      } else if (this.type === 'official') {
        let type1index = 1
        let type2index = 1
        this.candidateList.forEach((item, index, arr) => {
          switch (item.type) {
            case 1:
              arr[index].theType = item.participation ? 'success' : 'warning'
              arr[index].typename = '参训人员' + type1index
              type1index++
              break
            case 2:
              arr[index].theType = 'info'
              arr[index].typename = '备选人员' + type2index
              type2index++
              break
          }
        })
        this.formatPersonList = this.candidateList
      }
      if (parseInt(localStorage.getItem('trainingSelectId'))) {
        this.toggleSelection(parseInt(localStorage.getItem('trainingSelectId')))
      }
    }
  }
}
</script>
<style>
</style>
